package top.yongyan0624.service;

import top.yongyan0624.spring.BeanPostProcessor;
import top.yongyan0624.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Yongyan
 * @description Spring允许用户自定义一些Bean的后置处理
 * @date 2022/2/8 17:55
 **/

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if (bean instanceof UserService) {
            //AOP返回的是代理对象而不是真实对象
            return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑");
                    return method.invoke(bean, args);
                }
            });
        }
        //如果没有代理，则返回真实对象
        return bean;
    }
}
